// utils/request.js

// const baseUrl = 'https://wxapi.llshs.cn/wxd-api'; // 可以从配置文件读取

function request(path, data = {}, method = 'GET') {
  return new Promise((resolve, resolveWithTokenRefresh) => {
    const app = getApp();
    // 从本地存储中获取 token
    const token = wx.getStorageSync('token');
    const url = `${app.globalData.baseUrl}${path.startsWith('/') ? '' : '/'}${path}`;
    console.log('request url', url, data, method)
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {})
      },
      success: (res) => {
        console.log('request utils result: ', res)
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) { // Token 无效或过期
          refreshTokenAndRetry(path, data, method, resolveWithTokenRefresh);
        } else {
          console.error('Request failed with status:', res.statusCode);
          resolve({ error: 'Request failed', ...res.data });
        }
      },
      fail: (err) => {
        console.error('Network error:', err);
        resolve({ error: 'Network error', ...err });
      }
    });
  });
}

async function refreshTokenAndRetry(url, data, method, resolveWithTokenRefresh) {
  // const app = getApp();
  // const loginUrl = `${app.globalData.baseUrl}/login`;
  // console.log('login url ', loginUrl)
  try {
    const loginRes = await new Promise((resolve, reject) => {
      wx.login({
        success: resolve,
        fail: reject
      });
    });

    if (loginRes.errMsg !== 'login:ok') {
      throw new Error('Failed to get login code');
    }

    const jsCode = loginRes.code;

    // 使用 code 换取新的 token 和 openid
    const loginData = { jsCode };
    const res = await request('login', loginData, 'POST', { 'content-type': 'application/json' });

    console.log('re login result: ', res);

    if (res.code === 200 && res.data.token) {
      // 更新本地存储中的 token 和 openid
      wx.setStorageSync('token', res.data.token);
      wx.removeStorageSync('userInfo');

      // 重试原始请求
      const retryRes = await request(url, data, method);
      resolveWithTokenRefresh(retryRes);
    } else {
      console.error('Failed to refresh token:', res);
      resolveWithTokenRefresh({ error: 'Failed to refresh token', ...res });
    }
  } catch (err) {
    console.error('Failed to refresh token:', err);
    resolveWithTokenRefresh({ error: 'Failed to refresh token', ...err });
  }
}

module.exports = request;